import 'package:flutter/material.dart';
import 'package:hktk_app/decoration/chapter_tab_decoration.dart';
import 'package:hktk_app/util/view_util.dart';

/// 我的题库考试tabBar显示方法
class BankTitleWidget extends StatefulWidget {
  /// 控制器
  final TabController tabController;

  /// tab相关数据
  final List<String> tabList;

  const BankTitleWidget({
    super.key,
    required this.tabController,
    required this.tabList,
  });

  @override
  State<BankTitleWidget> createState() => _BankTitleWidgetState();
}

class _BankTitleWidgetState extends State<BankTitleWidget> {
  /// 选中的下标
  late int _index;

  @override
  void initState() {
    super.initState();
    _index = 0;

    // tab滑动点击监听
    widget.tabController.addListener(() {
      if (widget.tabController.index == widget.tabController.animation!.value) {
        int index = widget.tabController.index;
        // 选中样式切换
        if(mounted){
          setState(() {
            _index = index;
          });
        }

      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 32),
      height: 42,
      alignment: Alignment.topLeft,
      child: _tabBarItem(),
    );
  }

  /// tabBar组件
  _tabBarItem() {
    return TabBar(
      controller: widget.tabController,
      tabs: _tabItems(),
      // tab是否可以在水平方向上滚动
      isScrollable: true,
      // 从左到右进行排列，设置tab左侧对齐，去除左侧偏移
      tabAlignment: TabAlignment.start,
      // 分隔线高度
      dividerHeight: 0,
      // tab间距修改
      labelPadding: EdgeInsets.zero,
      // 选中样式
        indicator:BoxDecoration()
      // indicator: ChapterTagDecoration(
      //   isAtLast: _index == widget.tabList.length - 1,
      // ),
    );
  }

  /// 显示对应的tab
  _tabItems() {
    List<Widget> widgets = [];
    int length = widget.tabList.length;
    for (int i = 0; i < length; i++) {
      String name = widget.tabList[i];
      widgets.add(Tab(
        child: Padding(
          padding: EdgeInsets.only(right: i != length - 1 ? 18 : 10),
          child: Text(
            name,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w400,
              color: _index == i ? colorBlue1 : colorBlack1,
            ),
          ),
        ),
      ));
    }
    return widgets;
  }
}
